package com.amgl.amupush.news;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;

import com.amgl.amupush.data.News;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import timber.log.Timber;

/**
 * Created by amglh on 2016/8/10.
 */
public class NewsPresenter implements NewsContract.Presenter {
    private static final int TOTAL_PAGE = 5;
    private static final int PAGE_SIZE = 20;

    private int mCurrentPage = 0;

    NewsContract.NewsView mNewsView;
    Handler mHandler;

    public NewsPresenter(@NonNull NewsContract.NewsView newsView) {
        this.mNewsView = newsView;

        mNewsView.setPresenter(this);

        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void loadNews() {
        Timber.d("load new");
        final List<News> data = loadNews(0);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                mCurrentPage = 0;
                mNewsView.showNewData(data);
            }
        }, 3000);
    }

    @Override
    public void loadMore() {
        Timber.d("load more");
        final List<News> data = loadNews(mCurrentPage + 1);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mCurrentPage++;
                mNewsView.showMoreData(data);
            }
        }, 3000);
    }

    @Override
    public boolean isEndPage() {
        return (mCurrentPage >= TOTAL_PAGE);
    }

    @Override
    public int getPageSize() {
        return PAGE_SIZE;
    }

    private List<News> loadNews(int page) {
        Timber.d("load page %s", page);
        if (page >= TOTAL_PAGE) {
            isEndPage();
            return Collections.emptyList();
        }
        List<News> data = new ArrayList<>();
        for (int i = 0; i < PAGE_SIZE; i++) {
            News news = new News();
            news.id = page * 1000 + i;
            news.setTitle();
            data.add(news);
        }
        return data;
    }
}
